package org.example.gc;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试 STW (测试结果并不明显)
 * @author youshang
 * @date 2022/03/31 00:37
 **/
public class StopTheWorldTest {

    public static class WorkThread extends Thread {
        List<byte[]> list = new ArrayList<>();

        @Override
        public void run() {
            try {
                while (true) {
                    for (int i = 0; i < 1000; i++) {
                        byte[] bytes = new byte[1024];
                        list.add(bytes);
                    }
                    if (list.size() > 10000) {
                        list.clear();
                        System.gc();//原本设想的是通过 手调用gc 然后使其触发 STW，降低另外一个线程的执行时间 但是事实表明体现的并不明显
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public static class PrintThread extends Thread {
        public final long startTime = System.currentTimeMillis();


        @Override
        public void run() {
            try {
                while (true) {
                    long start = System.currentTimeMillis() - startTime;
                    System.out.println(start / 1000 + "." + start % 1000);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        WorkThread workThread = new WorkThread();
        PrintThread printThread = new PrintThread();


        //workThread.start();
        /*
        0.0
        1.2
        2.6
        3.16
        4.20
        5.23
        6.25
        7.30
        8.34
        9.36
        10.38
         */

        printThread.start();
        /*
        0.1
        1.4
        2.4
        3.6
        4.7
        5.9
        6.10
        7.14
        8.19
        9.20
        10.23
         */


    }
}
